import traceback

from flask import Blueprint, jsonify, request
import mysql.connector
from global_scope import DB_CONFIG
from tools import log_operations

db_bp = Blueprint("database", __name__, url_prefix='/db')


def get_db_connection(req):
    """
    创建并返回一个数据库连接。

    :return: 数据库连接对象或None
    """
    connection = None
    try:
        connection = mysql.connector.connect(**DB_CONFIG)
    except mysql.connector.Error as e:
        tb = traceback.format_exc()
        req.trace_logger.error(f"Exception occurred: {str(e)}\n{tb}")
    return connection


@db_bp.route('/test_db')
@log_operations
def test_db():
    """
    测试数据库连接的路由。

    :return: 数据库连接测试结果的响应
    """
    connection = get_db_connection(request)
    if connection is not None:
        connection.close()
        return jsonify({"message": "Database connection established successfully!"})
    else:
        return jsonify({"error": "Failed to connect to the database."}), 500
